package com.my.chapter15;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;

public class practice33 {
    public static void main(String[] args) {
        FixedSizeStack2<Integer> stack =
                new FixedSizeStack2<Integer>(1);
        stack.push(1);
        System.out.println(stack.pop());
        try {
            stack.pop();
        } catch(EmptyStackException e) {
            System.out.println(e.toString());
        }
        stack = new FixedSizeStack2<Integer>(1);
        stack.push(2);
        try {
            stack.push(2);
        } catch(FullStackException e) {
            System.out.println(e.toString());
        }
    }
}

class FullStackException extends RuntimeException {}

class FixedSizeStack2<T> {
    private int index;
    private final int size;
    private final List<T> storage;
    public FixedSizeStack2(int size) {
        storage = new ArrayList<T>(size);
        this.size = size;
    }
    public void push(T item) {
        if(index < size) {
            index++;
            storage.add(item);
        } else
            throw new FullStackException();
    }
    public T pop() {
        if(index > 0)
            return storage.get(--index);
        throw new EmptyStackException();
    }
}
